<template>
  <div class="app-container">
    <el-form ref="role" :model="role" :rules="validateRules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="role.name"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          :rows="2"
          v-model="role.remark"
          type="textarea"/>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import roleApi from '@/api/acl/role'

const defaultForm = {
  name: '',
  remark: ''
}

export default {
  data() {
    return {
      role: defaultForm,
      saveBtnDisabled: false,
      validateRules: {
        name: [{ required: true, trigger: 'blur', message: '角色名必须输入' }]
      }
    }
  },

  watch: {

    $route(to, from) {
      console.log('路由变化......')
      console.log(to)
      console.log(from)
      this.init()
    }

  },

  created() {
    this.init()
  },

  methods: {

    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        this.role = { ...defaultForm }
      }
    },

    saveOrUpdate() {
      this.$refs.role.validate(valid => {
        if (valid) {
          this.saveBtnDisabled = true
          if (!this.role.id) {
            this.saveData()
          } else {
            this.updateData()
          }
        }
      })
    },

    saveData() {
      roleApi.save(this.role).then(response => {
        if (response.success) {
          this.$message({
            type: 'success',
            message: response.result
          })
          this.$router.push({ path: '/acl/role/list' })
        }
      })
    },

    updateData() {
      roleApi.updateById(this.role).then(response => {
        if (response.success) {
          this.$message({
            type: 'success',
            message: response.result
          })
          this.$router.push({ path: '/acl/role/list' })
        }
      })
    },

    fetchDataById(id) {
      roleApi.getById(id).then(response => {
        this.role = response.result
      })
    }

  }
}
</script>
